//
//  SetViewController.m
//  LazyCat
//
//  Created by zhanshu on 15/9/14.
//  Copyright (c) 2015年 zhanshu. All rights reserved.
//

#import "SetViewController.h"
#import "AFNetworkHandler.h"
#import "MyMessTableViewCell.h"
#import "SoundChangeViewController.h"
#import "SearchBlueViewController.h"

@interface SetViewController ()<UITableViewDataSource,UITableViewDelegate>

{
    NSArray *imgArr;
    NSArray *tileArr;
    NSString *updateURL;
    NSString *_cachesMb;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation SetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    /********************/
    [self initNav:@"设置" doBack:YES];
    UIView *lineV = [[UIView alloc]initWithFrame:CGRectMake(0, 63, ScreenWidth, 1)];
    lineV.backgroundColor = [UIColor lightGrayColor];
    lineV.alpha = 0.2;
    [self.view addSubview:lineV];
    /********************/
    imgArr = @[@"2323_r2_c2.png",@"设置_r1_c1.png"];
    tileArr = @[@"关于我们",@"版本更新",@"清除缓存"];
    _tableView.tableFooterView = [[UIView alloc] init];
    _tableView.backgroundColor = BackColor;
    self.view.backgroundColor = [UIColor whiteColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.scrollEnabled = NO;
    UIButton *quitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    quitBtn.backgroundColor = [UIColor whiteColor];
    [quitBtn setTitle:@"退出登录" forState:UIControlStateNormal];
    quitBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [quitBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    quitBtn.frame = CGRectMake(0, 350, ScreenWidth, 40);
    [quitBtn addTarget:self action:@selector(quit) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:quitBtn];
    NSString * cachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
    _cachesMb = [NSString stringWithFormat:@"%.02fMB",[self folderSizeAtPath:cachePath]];
}
-(void)quit {//退出
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"是否退出" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag = 2000;
    [alert show];
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 2;
    }else{
    return tileArr.count;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *Cell = @"cell";
    MyMessTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Cell];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"MyMessTableViewCell" owner:self options:nil] firstObject];
    }
    cell.inputTextField.enabled = NO;
    cell.titleLable.font = [UIFont fontWithName:nil size:15];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    // 版本号
    NSString *currentVS =  [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            cell.titleLable.text = @"蓝牙打印机";
        }else {
            cell.titleLable.text = @"消息提醒";
        }
        cell.titleLable.font = [UIFont systemFontOfSize:15];
    }else{
        cell.titleLable.text = tileArr[indexPath.row];
        if (indexPath.row == 1) {
            UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth - 100, 15, 75, 20)];
            lab.textAlignment = NSTextAlignmentRight;
            lab.text = currentVS;
            lab.font = [UIFont fontWithName:nil size:15];
            [cell addSubview:lab];
        }else if (indexPath.row == 2){
            UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth - 100, 15, 75, 20)];
            lab.textAlignment = NSTextAlignmentRight;
            lab.text = _cachesMb;
            lab.font = [UIFont fontWithName:nil size:15];
            [cell addSubview:lab];
        }
    }
    return cell;
}



- (long long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}
//遍历文件夹获得文件夹大小，返回多少M
- (float ) folderSizeAtPath:(NSString*) folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) { // 消息提醒
        if (indexPath.row == 0) {
            SearchBlueViewController *search = [[SearchBlueViewController alloc] init];
            [self.navigationController pushViewController:search animated:YES];
        }else {
            SoundChangeViewController *sound = [[SoundChangeViewController alloc] init];
            [self.navigationController pushViewController:sound animated:YES];
        }
    }else{
        if (indexPath.row == 0) { // 关于我们
            Html5ViewController *html5 = [[Html5ViewController alloc] init];
            html5.doDetailType = YES;
            html5.doComeFromeHomeView = YES;
            html5.titleStr = @"关于我们";
            html5.requestUrl = [NSString stringWithFormat:businessAboutUs,[AppData share].username,[Utils md5SignStr]];
            NSLog(@"%@",html5.requestUrl);
            
            [self.navigationController pushViewController:html5 animated:YES];
        }else if (indexPath.row == 1){ // 版本更新
            [self getVersionMess]; // 版本更新
        }else if (indexPath.row == 2){ // 清除缓存
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:_cachesMb delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.tag = 1000;
            [alert show];
        }
    }
}
#pragma mark - 版本信息
- (void)getVersionMess {
    NSString *banbenID = @"1.0.1";
    NSString *url = @"";
    
    if ([banbenID isEqualToString:@"1"]) { // APPStore版本升级
        
        url = [NSString stringWithFormat:Updatestore,[Utils md5SignStr],@"1.0.2"];
        [NTNetUtil sendRequestWithUrl:url requestName:UpdateVersion method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
            NSDictionary *dic = networkRequest.responseData;
            NSString *suc = dic[@"r"];
            if ([suc isEqualToString:@"T"]) {
                NSDictionary *ios = dic[@"IOSstore"];
                //            NSString *currentVS =  [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
                
                NSString *need = [ios[@"need"] safeString];
                NSString *note = [ios[@"note"] safeString];
                NSString *title = [ios[@"title"] safeString];
                NSString *isnew = [ios[@"isnew"] safeString];
                if ([isnew isEqualToString:@"false"]) {
                    return ;
                }
                if ([need isEqualToString:@"false"]) {
                    //不强制
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:note delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"更新", nil];
                    alert.tag = 100;
                    [alert show];
                }else {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:note delegate:self cancelButtonTitle:@"更新" otherButtonTitles:nil, nil];
                    alert.tag = 101;
                    [alert show];
                }
                updateURL = [ios[@"url"] safeString];
            }
        }];
        //=======================================================================================
    }else{ // 企业版本号
        url = [NSString stringWithFormat:UpdateVersion,[Utils md5SignStr],@"1.0.4"];
        [NTNetUtil sendRequestWithUrl:url requestName:UpdateVersion method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
            NSDictionary *dic = networkRequest.responseData;
            NSLog(@"```````%@",dic);
            NSString *suc = dic[@"r"];
            if ([suc isEqualToString:@"T"]) {
                NSDictionary *ios = dic[@"iOS"];
                //            NSString *currentVS =  [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
                
                NSString *need = [ios[@"need"] safeString];
                NSString *note = [ios[@"note"] safeString];
                
                NSString *title = [ios[@"title"] safeString];
                NSString *isnew = [ios[@"isnew"] safeString];
                if ([isnew isEqualToString:@"false"]) {
                    [[MessShowView share] showWithMess:@"当前为最新版本"];
                    return ;
                }
                if ([need isEqualToString:@"false"]) {
                    //不强制
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:note delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"更新", nil];
                    alert.tag = 100;
                    [alert show];
                }else {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:note delegate:self cancelButtonTitle:@"更新" otherButtonTitles:nil, nil];
                    alert.tag = 101;
                    [alert show];
                }
                updateURL = [ios[@"url"] safeString];
            }
        }];
        
    }

}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 100) {
        if (buttonIndex == 1) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",updateURL]]];
        }
    }else if(alertView.tag == 1000){ // 缓存
        if (buttonIndex == 1) {
//            NSString * cachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
//                NSFileManager * manager = [NSFileManager defaultManager];
//                [manager removeItemAtPath:cachePath error:nil];
//            _cachesMb = [NSString stringWithFormat:@"%.02fMB",[self folderSizeAtPath:cachePath]];
//            _cachesMb = @"0.00MB";
//            [_tableView reloadData];
//            [NSUserDefualManager storageValue:@"" forKey:UserName];
            NSString * cachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
            [self clearCache:cachePath];
            NSString * cachePath1 = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
            _cachesMb = [NSString stringWithFormat:@"%.02fMB",[self folderSizeAtPath:cachePath1]];
//            _cachesMb = @"0.00MB";
            [_tableView reloadData];
//            [NSUserDefualManager storageValue:@"" forKey:UserName];
        }
    }else if(alertView.tag == 2000){ // 退出登录
        if (buttonIndex == 1) {
        NSString *cid = [ NSUserDefualManager getValueByKey:@"cid"];
        NSString *url = [NSString stringWithFormat:businessLoginOut,cid,[AppData share].username];
        [AFNetworkHandler GETWithAFNByURL:url completion:^(id result) {
            NSDictionary *dict = result;
            NSString *r = dict[@"r"];
            if ([r isEqualToString:@"T"]) {
                [[AppData share] clearValue];
//                [NSUserDefualManager storageValue:@"" forKey:UserName];
                [NSUserDefualManager storageValue:@"" forKey:Psw];
                [AppData share].baseTabVC.redLable.hidden = YES;
                [NSUserDefualManager storageValue:@"0" forKey:@"doLogin"];
                NSUserDefaults *userDefaul = [NSUserDefaults standardUserDefaults]; // 蓝牙开关状态
                [userDefaul setObject:@"off" forKey:@"switch"];
                LoginViewController *loginVC = [[LoginViewController alloc]init];
                [self presentViewController:loginVC animated:YES completion:^{
                    
                }];
            }else {
                [[MessShowView share] showWithMess:dict[@"m"]];
            }
        }];
        }
    }else{
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://%@",updateURL]]];
    }
}
-(void)clearCache:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles=[fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            //如有需要，加入条件，过滤掉不想删除的文件
            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
            [fileManager removeItemAtPath:absolutePath error:nil];
        }
    }
    [[SDImageCache sharedImageCache] cleanDisk];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
